package vn.co.thn.android.store.activity;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import vn.co.thn.android.store.NSConstants;
import vn.co.thn.android.store.R;
import vn.co.thn.android.store.adapter.NSPlacesAutoCompleteAdapter;
import vn.co.thn.android.store.data.NSLocationItemData;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

public class NSSearchAddressActivity extends NSCommonActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener,
		OnMyLocationButtonClickListener {
	private GoogleMap mMap;
	private LocationClient mLocationClient;
	private NSLocationItemData location;
	private String TAG="NSSearchAddressActivity";
	private static final LocationRequest REQUEST = LocationRequest.create().setInterval(5000) // 5
																								// seconds
			.setFastestInterval(16) // 16ms = 60fps
			.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ns_search_address_on_map_activity);
		findViewById(R.id.return_address).setOnClickListener(this);
		AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.search_target);
        autoCompView.setAdapter(new NSPlacesAutoCompleteAdapter(this, android.R.layout.test_list_item
        		));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.return_address:
			LatLng latLng = mMap.getCameraPosition().target;
			location=new NSLocationItemData();
			double lat = latLng.latitude;
			double lng = latLng.longitude;
			location.setLatitude(lat);
			location.setLongitude(lng);
			Location l=new Location("test");
			l.setLatitude(lat);
			l.setLongitude(lng);
			(new GetAddressTask(this)).execute(l);
		
			break;

		default:
			break;
		}
	}

	private void setUpMap() {
		if (mMap == null) {
			mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

			if (mMap != null) {
				mMap.setMyLocationEnabled(true);
				mMap.setOnMyLocationButtonClickListener(this);
			}
		}
	}

	private void setUpLocationClient() {
		if (mLocationClient == null) {
			mLocationClient = new LocationClient(this, this, // ConnectionCallbacks
					this); // OnConnectionFailedListener
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setUpMap();
		setUpLocationClient();
		mLocationClient.connect();
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mLocationClient != null) {
			mLocationClient.disconnect();
		}
	}

	@Override
	public boolean onMyLocationButtonClick() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onConnected(Bundle arg0) {
		// TODO Auto-generated method stub
		mLocationClient.requestLocationUpdates(REQUEST, this);
		
		if (mLocationClient != null && mLocationClient.isConnected()) {
			try{
			Toast.makeText(NSSearchAddressActivity.this, "Connected", Toast.LENGTH_SHORT).show();
    	    Location location = mLocationClient.getLastLocation();
    	    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    	    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
    	    mMap.animateCamera(cameraUpdate); 	
			}catch(Exception e){
				e.printStackTrace();
				Log.e(TAG, "Location Error");
			}
	    Handler handler=new Handler();
	    Runnable r=new Runnable()
	    {
	        public void run() 
	        {
	        	Toast.makeText(NSSearchAddressActivity.this, "Connected", Toast.LENGTH_SHORT).show();
	    	    Location location = mLocationClient.getLastLocation();
	    	    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
	    	    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
	    	    mMap.animateCamera(cameraUpdate); 			
	        }
	    };
	    handler.postDelayed(r, 5000);
		}
	}

	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub

	}

	private class GetAddressTask extends AsyncTask<Location, Void, String> {
		Context mContext;

		public GetAddressTask(Context context) {
			super();
			mContext = context;
		}

		@Override
		protected String doInBackground(Location... params) {
			Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
			Location loc = params[0];
			List<Address> addresses = null;
			try {
				/*
				 * Return 1 address.
				 */
				addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
			} catch (IOException e1) {
				Log.e("LocationSampleActivity", "IO Exception in getFromLocation()");
				e1.printStackTrace();
				return ("IO Exception trying to get address");
			} catch (IllegalArgumentException e2) {
				// Error message to post in the log
				String errorString = "Illegal arguments " + Double.toString(loc.getLatitude()) + " , " + Double.toString(loc.getLongitude())
						+ " passed to address service";
				Log.e("LocationSampleActivity", errorString);
				e2.printStackTrace();
				return errorString;
			}
			if (addresses != null && addresses.size() > 0) {
				// Get the first address
				Address address = addresses.get(0);
				/*
				 * Format the first line of address (if available), city, and
				 * country name.
				 */
				String addressText = String.format("%s, %s, %s",
				// If there's a street address, add it
						address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
						// Locality is usually a city
						address.getLocality(),
						// The country of the address
						address.getCountryName());
//				String addressText="";
//				for(int i=0;i<address.getMaxAddressLineIndex();i++){
//					addressText=addressText+address.getAddressLine(i)+",";
//				}
				// Return the text
				return addressText;
			} else {
				return null;
			}
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			location.setAddress(result);
			Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
			Intent intent=new Intent();
			intent.putExtra(NSConstants.ADDRESS_SEARCH, location);
			setResult(RESULT_OK, intent);
			finish();
		}
	}
}
